package com.yanqu.road.server.cmd.union.activitygroup;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.cross.CrossUnionInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.rank.RankProto;
import com.yanqu.road.pb.union.UnionActivityGroupProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manager.union.activitygroup.Cross3UnionActivityGroupMgr;
import com.yanqu.road.server.manager.union.activitygroup.UnionActivityGroupLockMgr;
import com.yanqu.road.server.manager.union.unionrank.CrossUnionRankMsgCacheMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Cmd(code = CrossProtocol.C_UNION_ACTIVITY_GROUP_GET_UNION_RANK, desc = "活动范围内商会排名")
public class CrossUnionActivityGroupGetUnionRankCmd extends CrossCommand {

    private UnionActivityGroupProto.UnionActivityGroupGetUnionRankReqMsg reqMsg;
    private int activityId;
    private int type;
    private int pageNo;
    private int pageSize;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        reqMsg = UnionActivityGroupProto.UnionActivityGroupGetUnionRankReqMsg.parseFrom(packet.getBytes());
        activityId = reqMsg.getActivityId();
        type = reqMsg.getType();
        pageNo = reqMsg.hasPageNo() ? reqMsg.getPageNo() : 0;
        pageSize = reqMsg.hasPageSize() ? reqMsg.getPageSize() : 200;
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        long userId = packet.getPlayerId();
        String unionUid = "";
        String myValue = "0";
        List<CrossUnionInfo> infoList = new ArrayList<>();
        int myRank = -1;
        ActivityInfo activityInfo = UnionActivityGroupLockMgr.getActivityInfoMap().get(activityId);
        if (activityInfo == null) {
            return;
        }

        // 取玩家当前商会UID和赚速（退出、解散去也是取当前）
        CrossUnionMember unionMember = CrossUnionMgr.getUnionMemberByUserId(userId);
        if (unionMember != null && !StringUtils.isNullOrEmpty(unionMember.getUnionUid())) {
            unionUid = unionMember.getUnionUid();
            CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(unionUid);
            if (unionInfo != null) {
                myValue = unionInfo.getTotalEarnSpeed().toString();
                // v6.9 隋唐改为赚钱
                if (activityInfo.getType() == eActivityType.SuiTang.getValue()
                || activityInfo.getType() == eActivityType.ChuHanZB.getValue()
                        || activityInfo.getType() == eActivityType.FiveHero.getValue()) {
                    myValue = unionInfo.getTotalMaxAbility().toString();
                }
            }
        }

        RankProto.UnionRankListMsg.Builder rankBuilder = RankProto.UnionRankListMsg.newBuilder();

        if (type == 1) { // 活动范围内所有商会榜单
            RankProto.UnionRankListMsg saveRankMsg = CrossUnionRankMsgCacheMgr.getUnionActivityRankMsgByActivityId(activityId);

            if (saveRankMsg != null){
                int beginIndex = pageNo * pageSize;
                int endIndex = (pageNo + 1) * pageSize;

                for (int i = beginIndex; i < endIndex && i < saveRankMsg.getRankListList().size(); i++) {
                    RankProto.UnionRankTempMsg rankTempMsg = saveRankMsg.getRankList(i);
                    rankBuilder.addRankList(rankTempMsg.toBuilder());
                }

                for (int i = 0; i < saveRankMsg.getRankListList().size(); i++) {
                    int rank = i + 1;
                    RankProto.UnionRankTempMsg rankTempMsg = saveRankMsg.getRankList(i);
                    if (rankTempMsg.getUnionUid().equals(unionUid)) {
                        myRank = rank;
                        break;
                    }
                }
            }
        } else if (type == 2) { // 分组内所有商会榜单
            int groupId = Cross3UnionActivityGroupMgr.getGroupId(activityId, userId);
            if (groupId != UnionActivityGroupHelper.NO_GROUP_ID) {
                UnionActivityGroup group = Cross3UnionActivityGroupMgr.getGroupData(activityId, groupId);
                for (UnionActivityGroupUnion union : group.getUnionDataMap().values()) {
                    CrossUnionInfo unionInfo = CrossUnionMgr.getUnionInfo(union.getUnionUid());
                    if (unionInfo == null) {
                        CrossUnionMgr.getDeleteUnionInfoMap().get(union.getUnionUid());
                    }
                    if (unionInfo == null) {
                        continue;
                    }
                    infoList.add(unionInfo);
                }
            }
            // v6.9 隋唐改为赚钱
            if (activityInfo.getType() == eActivityType.SuiTang.getValue()
                    || activityInfo.getType() == eActivityType.ChuHanZB.getValue()
                    || activityInfo.getType() == eActivityType.FiveHero.getValue()) {
                infoList.sort(Comparator.comparing(CrossUnionInfo::getTotalMaxAbility).reversed());
            } else {
                infoList.sort(Comparator.comparing(CrossUnionInfo::getTotalEarnSpeed).reversed());
            }

            int beginIndex = pageNo * pageSize;
            int endIndex = (pageNo + 1) * pageSize;

            for (int i = beginIndex; i < endIndex && i < infoList.size(); i++) {
                CrossUnionInfo unionInfo = infoList.get(i);
                RankProto.UnionRankTempMsg.Builder builder = RankProto.UnionRankTempMsg.newBuilder();
                builder.setUnionUid(unionInfo.getUnionUid());
                builder.setUnionBaseData(UnionBasePb.parseUnionBaseTempMsg(CrossUnionMgr.parseUnionBaseInfo(unionInfo)));
                // v6.9 隋唐改为赚钱
                if (activityInfo.getType() == eActivityType.SuiTang.getValue()
                        || activityInfo.getType() == eActivityType.ChuHanZB.getValue()
                        || activityInfo.getType() == eActivityType.FiveHero.getValue()) {
                    builder.setValue(unionInfo.getTotalMaxAbility().toString());
                } else {
                    builder.setValue(unionInfo.getTotalEarnSpeed().toString());
                }
                rankBuilder.addRankList(builder);
            }


            int rank = 0;
            for (CrossUnionInfo info : infoList) {
                rank++;
                if (info.getUnionUid().equals(unionUid)) {
                    myRank = rank;
                    break;
                }
            }
        }

        UnionActivityGroupProto.UnionActivityGroupGetUnionRankRespMsg.Builder builder = UnionActivityGroupProto.UnionActivityGroupGetUnionRankRespMsg.newBuilder();
        builder.setRet(0);
        builder.setMyRank(myRank);
        builder.setValue(myValue);
        builder.setRankList(rankBuilder);
        YanQuMessage message = YanQuMessageUtils.buildMessage(ClientProtocol.U_UNION_ACTIVITY_GROUP_GET_UNION_RANK, builder);
        MessageHelper.sendPacket(serverId, userId, message);
    }

    @Override
    public void sendData() {
    }
}
